//
//  HAWebVC.m
//  HA
//
//  Created by sy on 2023/12/17.
//

#import "HAWebVC.h"
#import <WebKit/WebKit.h>

@interface HAWebVC ()<WKNavigationDelegate>

/// WKWebView
@property (nonatomic, strong) WKWebView *wkWebView;
/// 进度条
@property (nonatomic, strong) UIProgressView *progressView;

@end

@implementation HAWebVC


-(void)viewWillAppear:(BOOL)animated {

}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

}

-(void)dealloc {
    self.wkWebView.navigationDelegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
//    [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.wkWebView];
    [self.view addSubview:self.progressView];
    
    self.wkWebView.navigationDelegate = self;
    // KVO
    [self.wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
    
    if (![NSString isEmptyString:self.tit]) {
        self.baseTLabel.text = self.tit;
    }
    
    if ([NSString isEmptyString:self.urlStr]) {
        [MBProgressHUD showError:@"将于3秒后关闭页面..."];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        return;
    }

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:self.urlStr]];
    [self loadRequest:request];
    
    // Do any additional setup after loading the view.
}

-(void)ha_leftButtonClick {
    if ([self.wkWebView canGoBack]) {
        [self.wkWebView goBack];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.allowsInlineMediaPlayback = YES;
        CGFloat y = app_topH+44;
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, y, kUIScreen_w, kUIScreen_h-y) configuration:configuration];
    }
    return _wkWebView;
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.trackTintColor = [UIColor colorWithHexString:@"#ffffff"];
        // 高度默认有导航栏且有穿透效果
        CGFloat y = app_topH+44;
        _progressView.frame = CGRectMake(0, y, kUIScreen_w, 2);
        // 设置进度条颜色
        _progressView.tintColor = [UIColor colorWithHexString:@"#999999"];
    }
    return _progressView;
}

/// KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
        self.progressView.alpha = 1.0;
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        if(self.wkWebView.estimatedProgress >= 0.97) {
            [UIView animateWithDuration:0.1 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.progressView.alpha = 0.0;
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0 animated:NO];
            }];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - - - 加载的状态回调（WKNavigationDelegate）
/// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
}
/// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}
/// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    self.progressView.alpha = 0.0;
}
/// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.alpha = 0.0;
}


-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.alpha = 0.0;
}

/// 加载 web
- (void)loadRequest:(NSURLRequest *)request {
    [self.wkWebView loadRequest:request];
}
/// 加载 HTML
- (void)loadHTMLString:(NSString *)HTMLString {
    [self.wkWebView loadHTMLString:HTMLString baseURL:nil];
}
/// 刷新数据
- (void)reloadData {
    [self.wkWebView reload];
}



@end
